﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using TMS_BackEnd.IServices.He;
using TMS_BackEnd.Models.He;
using TMS_BackEnd.Options;

namespace TMS_BackEnd.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class Sys_userController : ControllerBase
    {
        private readonly IOptions<JWTOptions> options;

        public ISysUserService sysUser { get; set; }

        public Sys_userController(IOptions<JWTOptions> options)
        {
            this.options = options;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="uname"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetLogin(string uname, string pass)
        {
            if(sysUser.GetLogin(uname, pass))
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Name, uname));
                claims.Add(new Claim(ClaimTypes.Role, "admin"));
                string jwtToken = BuildToken(claims, options.Value);
                return Ok(new
                {
                    code = 1,
                    message = "登录成功",
                    value = jwtToken
                });
            }
            else
            {
                return Ok(new
                {
                    code = -1,
                    message = "用户名或密码错误"
                });
            }
        }

        private static string BuildToken(IEnumerable<Claim> claims, JWTOptions options)
        {
            DateTime expires = DateTime.Now.AddSeconds(options.ExpireSeconds);
            //读取加密算法
            SymmetricSecurityKey secKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.SigningKey));
            //指定加密算法
            SigningCredentials credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
            //创建jwt
            JwtSecurityToken tokenDescriptor = new JwtSecurityToken(expires: expires, signingCredentials: credentials, claims: claims);
            return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
        }

    }
}
